import { NextRequest, NextResponse } from 'next/server';
import { loginUser } from '@/lib/auth';
import { initDataFiles, initDefaultCategories } from '@/lib/data';
import { initAdminUser } from '@/lib/init';

export async function POST(request: NextRequest) {
  try {
    initDataFiles();
    initDefaultCategories();
    await initAdminUser();
    
    const { username, password } = await request.json();
    
    // 调试信息：检查是否是管理员账户登录尝试
    const adminUsername = process.env.ADMIN_USERNAME?.trim();
    if (username === adminUsername) {
      console.log(`[登录] 管理员账户登录尝试: ${username}`);
    }

    if (!username || !password) {
      return NextResponse.json(
        { success: false, message: '用户名和密码不能为空' },
        { status: 400 }
      );
    }

    const result = await loginUser(username, password);
    
    if (!result.success) {
      return NextResponse.json(result, { status: 401 });
    }

    const response = NextResponse.json(result);
    // 设置 Cookie
    response.cookies.set('token', result.token!, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7天
    });

    return response;
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '登录失败' },
      { status: 500 }
    );
  }
}

